package com.joe.demo.chat.server.handler;

import com.joe.demo.chat.message.LoginRequestMessage;
import com.joe.demo.chat.message.LoginResponseMessage;
import com.joe.demo.chat.server.factory.SessionFactory;
import com.joe.demo.chat.server.factory.UserServiceFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Description
 * @Author gaojw
 * @Date 2024-08-30
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, LoginRequestMessage loginRequestMessage) throws Exception {
        final String username = loginRequestMessage.getUsername();
        final String password = loginRequestMessage.getPassword();
        final boolean login = UserServiceFactory.getUserService().login(username, password);
        LoginResponseMessage message;
        if (login) {
            SessionFactory.getSession().bind(channelHandlerContext.channel(), username);
            message = new LoginResponseMessage(true, "登录成功");

        } else {
            message = new LoginResponseMessage(false, "登录失败，用户名或密码不正确！");
        }
        channelHandlerContext.writeAndFlush(message);
    }
}
